import 'dart:convert';
import 'dart:math';

import 'package:flutter/material.dart';
import 'package:flutter_application_cyber/model/cn_net_response.dart';
import 'package:flutter_application_cyber/net/cn_net_helper.dart';
import 'package:flutter_application_cyber/pages/Mine/Models/cn_BlockListModel.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:flutter_util_code/toast_utils.dart';
import 'package:flutter_application_cyber/model/cn_anchor_model.dart';
import 'package:flutter_application_cyber/tools/cn_database_helper.dart';
import '../../tools/cn_event_bus.dart';
import '../../tools/cn_click_utils.dart';

class CnBlockList extends StatefulWidget {
  const CnBlockList({super.key});
  @override
  State<CnBlockList> createState() => _BlockList();
}

class _BlockList extends State<CnBlockList> {
  List blockList = [];
  String showDataStatus = 'data';
  List homeImageList = [
    ['assets/homeImages/a_10001.jpg', 'assets/homeImages/a_10002.jpg'],
    ['assets/homeImages/b_10001.jpg', 'assets/homeImages/b_10002.jpg'],
    [
      'assets/homeImages/c_10001.jpg',
      'assets/homeImages/c_10002.jpg',
      'assets/homeImages/c_10003.jpg'
    ],
    ['assets/homeImages/d_10001.jpg', 'assets/homeImages/d_10002.jpg'],
    [
      'assets/homeImages/e_10001.jpg',
      'assets/homeImages/e_10002.jpg',
      'assets/homeImages/e_10003.jpg'
    ],
    ['assets/homeImages/f_10001.jpg', 'assets/homeImages/f_10002.jpg'],
    [
      'assets/homeImages/g_10001.jpg',
      'assets/homeImages/g_10002.jpg',
      'assets/homeImages/g_10003.jpg'
    ],
    [
      'assets/homeImages/h_10001.jpg',
      'assets/homeImages/h_10002.jpg',
      'assets/homeImages/h_10003.jpg'
    ],
    [
      'assets/homeImages/i_10001.jpg',
      'assets/homeImages/i_10002.jpg',
      'assets/homeImages/i_10003.jpg'
    ],
    [
      'assets/homeImages/j_10001.jpg',
      'assets/homeImages/j_10002.jpg',
      'assets/homeImages/j_10003.jpg'
    ],
    [
      'assets/homeImages/k_10001.jpg',
      'assets/homeImages/k_10002.jpg',
      'assets/homeImages/k_10003.jpg'
    ],
    ['assets/homeImages/l_10001.jpg', 'assets/homeImages/l_10002.jpg'],
  ];

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          backgroundColor: Colors.white,
          leading: const BackButton(color: Colors.black),
          title: const Text(
            'Blocked List',
            style: TextStyle(color: Colors.black, fontSize: 18),
          ),
        ),
        body: _buildContext());
  }

  Widget _buildContext() {
    switch (showDataStatus) {
      case 'noData':
        return Center(
          child: Text('No noData'),
        );
      case 'data':
        return Column(
          children: <Widget>[
            Expanded(
                child: Stack(
              children: [
                Container(
                  constraints: BoxConstraints(maxHeight: 1000),
                  child: ListView.builder(
                      scrollDirection: Axis.vertical, // 滚动方向
                      itemCount: blockList.length,
                      itemBuilder: (context, index) {
                        var model = blockList[index];
                        return Container(
                            height: 76,
                            child: Row(
                              mainAxisAlignment: MainAxisAlignment.spaceBetween,
                              children: [
                                Row(
                                  children: [
                                    Container(
                                      margin:
                                          EdgeInsets.only(left: 16, right: 10),
                                      width: 46,
                                      height: 46,
                                      clipBehavior: Clip.hardEdge,
                                      decoration: BoxDecoration(
                                          borderRadius:
                                              BorderRadius.circular(23)),
                                      child: Image.network(
                                        model.avatar,
                                        fit: BoxFit.cover,
                                      ),
                                    ),
                                    Text(
                                      '${getSubString(end: 8, str: model.nickName ?? "")}',
                                      style: TextStyle(
                                          fontSize: 16,
                                          color: Color(0xFF202020)),
                                      maxLines: 1,
                                      overflow: TextOverflow.ellipsis,
                                    ),
                                  ],
                                ),
                                InkWell(
                                  onTap: () {
                                    if (!CnClickUtils.isClick()) return;
                                    postRemoveRecord(model?.broadcasterId ?? "",
                                        (bool status) {
                                      if (status) {
                                        getHostLeaderboardData();
                                        int index = Random().nextInt(12);
                                        CnDatabaseHelper.getInstance()
                                            ?.insertAnchorRecord(
                                                nickname: model.nickName,
                                                userId: model.broadcasterId,
                                                avatar: model.avatar,
                                                country: model.registerCountry,
                                                imageMapPaths:
                                                    homeImageList[index]
                                                        .join(','),
                                                gender: 0,
                                                callCoins: 12,
                                                age: model.age,
                                                followNum: 10,
                                                isFollow: false);
                                      } 
                                    });
                                  },
                                  child: Container(
                                      margin: const EdgeInsets.only(right: 16),
                                      alignment: Alignment.center,
                                      width: 72,
                                      height: 30,
                                      decoration: const BoxDecoration(
                                          image: DecorationImage(
                                              image: AssetImage(
                                                  'images/icon_btn_bg_comment.png'),
                                              fit: BoxFit.cover)),
                                      child: const Text(
                                        'Unblock',
                                        style: TextStyle(
                                          color: Color(0xFFFFFFFF),
                                          fontSize: 12,
                                        ),
                                        textAlign: TextAlign.center,
                                      )),
                                ),
                              ],
                            ));
                      }),
                )
              ],
            ))
          ],
        );
      default:
        return Center(
          child: CircularProgressIndicator(
            color: Colors.white,
          ),
        );
    }
  }

  @override
  void initState() {
    super.initState();
    getHostLeaderboardData();
  }

  @override
  void dispose() {
    // TODO: implement dispose
    super.dispose();
    CnEventBus.instance!.commit(EventKeys.HomeListPageMessage, null);
  }

  void getHostLeaderboardData() {
    EasyLoading.show(status: 'loading...');

    CnNetHelper.getBlockListData(
        (HDHResponseData configData, bool result, String msg) {
      EasyLoading.dismiss();
      blockList.clear();
      if (result) {
        CnBlockListModel model =
            CnBlockListModel.coverFromJson(configData.data);
        List list = model.data ?? [];
        if (list.isNotEmpty) {
          setState(() {
            blockList = list;
            showDataStatus = 'data';
          });
        } else {
          setState(() {
            blockList = list;
            showDataStatus = 'noData';
          });
        }
      }
    });
  }

  //解除屏蔽主播
  void postRemoveRecord(String userId, Function callback) async {
    CnNetHelper.postRemoveRecord(userId,
        (HDHResponseData configData, bool result, String msg) {
      callback(result);
    });
  }
}

typedef FunctionTest<String> = void Function(String isSure);
//字符串截取
String getSubString({required int end, required String str}) {
  if (str.length > end) {
    return "${str.substring(0, end)}...";
  } else {
    return str;
  }
}
